package com.shujia.wyh.moniqiefen2;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapThread implements Runnable{
    private File file;
    public int num;

    MapThread(File file,int num){
        this.file = file;
        this.num = num;
    }

    @Override
    public void run() {
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            //创建一个map集合
            HashMap<String, Integer> map = new HashMap<>();
            //创建字符缓冲输入流对象
            br = new BufferedReader(new FileReader(file.getAbsolutePath()));
            String line = null;
            while ((line=br.readLine())!=null){
                //切分数据，得到班级
                String clazz = line.split(",")[4];
                if(map.containsKey(clazz)){
                    map.put(clazz,map.get(clazz)+1);
                }else {
                    map.put(clazz,1);
                }
            }

            //创建字符缓冲输出流对象，将一个map任务结果写入到一个文件中
            bw = new BufferedWriter(new FileWriter("hadoop/src/main/java/com/shujia/wyh/moniqiefen2/part_ms/part-m-" + num));
            //遍历集合写数据
            Set<Map.Entry<String, Integer>> entries = map.entrySet();
            for (Map.Entry<String, Integer> entry : entries) {
                String clazz = entry.getKey();
                Integer number = entry.getValue();
                bw.write(clazz+" "+number);
                bw.newLine();
                bw.flush();
            }
            System.out.println("part-m-" + num+"  任务完毕！");

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
